/**
 * 案例展示、新闻中心文章编辑新增组件
 */
'use strict';
import React, {
    Component
} from 'react'
import {
    Link,
} from 'react-router'
import {
    getImgInfo,
    uploadImgs
} from '../Tools'
import {
    ControlLabel,
    FormControl,
    HelpBlock,
    FormGroup,
    Button,
    Radio,
    Form
} from 'react-bootstrap'
import FieldGroup from './common/fieldGroup'

export default class article extends Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };
    constructor(props){
        super(props);
        this.state = {
            type: this.props.params.type,
            id: this.props.params.id,
            infoData: {},
            UE: '',
            imgData: {
                updateImg: true,
                showImg: false,
                imgUrl:''
            }
        }
    }

    componentDidMount() {
        let ue = UE.getEditor('editor'),{id,type} = this.state;//初始化富文本
        this.setState({UE: ue});
        if(id&&type==1){
            this.getNews(id);
        }else if(id&&type==2){
            this.getSchools(id);
        }else if(id&&type==3){
            this.getEcosphere(id);
        }else if(id&&type==4){
            this.getCooperativePartner(id);
        }
    }

    /**
     * 获取新闻
     */
    getNews(id){
        $.ajax({
            url: '/newsCenter/get/'+id,
            type: 'get',
            dataType: "json",
            success: function(data){
                if(data.code==200){
                    this.setState({infoData:data.data?data.data:{}});
                    this.setForm(data.data);
                }else{
                    alert(data.msg);
                }
            }.bind(this)
        });
    }
    /**
     * 获取学校（案例）
     */
    getSchools(id){
        $.ajax({
            url: '/caseDisplay/get/'+id,
            type: 'get',
            dataType: "json",
            success: function(data){
                if(data.code==200){
                    this.setState({infoData:data.data?data.data:{}});
                    this.setForm(data.data);
                }else{
                    alert(data.msg);
                }
            }.bind(this)
        });
    }
    /**
     * 获取合作政策
     */
    getEcosphere(id){
        $.ajax({
            url: '/cooperationPolicy/get/'+id,
            type: 'get',
            dataType: "json",
            success: function(data){
                if(data.code==200){
                    this.setState({infoData:data.data?data.data:{}});
                    this.setForm(data.data);
                }else{
                    alert(data.msg);
                }
            }.bind(this)
        });
    }
    /**
     * 获取合作伙伴
     */
    getCooperativePartner(id){
        $.ajax({
            url: '/cooperationPartner/get/'+id,
            type: 'get',
            dataType: "json",
            success: function(data){
                if(data.code==200){
                    this.setState({infoData:data.data?data.data:{}});
                    this.setForm(data.data);
                }else{
                    alert(data.msg);
                }
            }.bind(this)
        });
    }

    /**
     * 设置表单数据
     * @param data
     */
    setForm(data){
        let {UE,type} = this.state;
        if(data){
            document.querySelector('#title').value = data.title;
            if(data.top==0){
                document.querySelectorAll('[name=top]')[1].setAttribute('checked','checked');
            }else{
                document.querySelectorAll('[name=top]')[0].setAttribute('checked','checked');
            }

            if(data.isShow==0){
                document.querySelectorAll('[name=show]')[1].setAttribute('checked','checked');
            }else {
                document.querySelectorAll('[name=show]')[0].setAttribute('checked','checked');
            }

            document.querySelector('#introduce').value = data.introduce;
            UE.ready(function() {//编辑器初始化完成再赋值
                UE.setContent(decodeURIComponent(data.content));  //赋值给UEditor
            });
            if(type==1 || type==4 ){
                this.setState({
                    imgData: {
                        updateImg: false,
                        showImg: true,
                        imgUrl: data.imgUrl
                    }
                })
            }
        }
    }

    /**
     * 新增、编辑文章
     */
    addArticle(even){
        even.preventDefault();
        let {UE,imgData,id,type} = this.state;
        let isTop = $("input[name='top']:checked").val();//获取值是否置顶
        let isShow = type!=3?$("input[name='show']:checked").val():'';//获取值是否显示
        let title = $("#title").val();
        let introduce = $("#introduce").val();
        let content = UE.getContent();//获取编辑的内容

        if((type==1||type==4) && imgData.imgUrl==''){
            alert('请上传图片！');
            return;
        }
        if(title==''){
            alert('标题不能为空！');
            return;
        }
        if(isTop==undefined){
            alert('请设置是否置顶！');
            return;
        }
        if(isShow==undefined){
            alert('请设置是否显示！');
            return;
        }
        if(introduce==''){
            alert('简介不能为空！');
            return;
        }
        if(content==''){
            alert('文章内容不能为空！');
            return;
        }else{
            content = content.replace(/<table/g,'<div style="overflow: auto;  width: 100%;"><table');
            content = content.replace(/<\/table>/g,'<\/table><\/div>');
            content = encodeURIComponent(content);
        }
        let formData = new FormData(),url = '';
        formData.append('title',title);
        formData.append('content',content);
        formData.append('introduce',introduce);
        formData.append('isTop',isTop);
        if(id){//编辑
            formData.append('id',id);
            if(type==3||type==2){
                if(type==2){//案例学校
                    url = '/caseDisplay/update'
                }else if(type==3){//合作政策
                    url = '/cooperationPolicy/update'
                }

            }else{
                formData.append('isShow',isShow);
                if(imgData.updateImg){
                    formData.append('imgUrl',uploadImgs(document.getElementById('weAboutEnglishImage').files[0]));
                }else{
                    formData.append('imgUrl',imgData.imgUrl);
                }
                if(type==1){//新闻
                    url = '/newsCenter/update'
                }else if(type==4){//合作伙伴
                    url = '/cooperationPartner/update'
                }
            }
            this.requestAjax(url,formData);
        }else{//新增
            if(type==3||type==2){
                if(type==2){//案例学校
                    url = '/caseDisplay/add'
                }else if(type==3){//合作政策
                    url = '/cooperationPolicy/add'
                }
            }else{
                formData.append('isShow',isShow);
                formData.append('imgUrl',uploadImgs(document.getElementById('weAboutEnglishImage').files[0]));
                if(type==1){//新闻
                    url = '/newsCenter/add';
                }else if(type==4){//合作伙伴
                    url = '/cooperationPartner/add';
                }
            }
            this.requestAjax(url,formData);
        }
    }

    /**
     * 请求数据
     * @param url
     * @param formData
     */
    requestAjax(url, formData){
        $.ajax({
            url: url,
            type: 'post',
            data: formData,
            dataType: "json",
            timeout: 0,//请求时间
            contentType:false,//则数据再发送器会被转换成查询字符串通过false来回避
            processData: false,//禁发送数据格式自动转换
            success: function(data){
                if(data.code==200){
                    alert('操作成功！');
                }else{

                }
            }.bind(this)
        });
    }
    /**
     * 选择图片
     * @param e
     */
    onChangFile(e) {
        let fileUrl = e.target.value.split('\\'),{id,type} = this.state;//注split可以用字符或字符串分割
        let fileName = fileUrl[fileUrl.length-1];//这就是要取得的图片名称
        let fileLat = fileName.substring( fileName.lastIndexOf('.')+1 );//后缀名称
        if(fileLat == "png" || fileLat == "jpg" || fileLat == "gif" || fileLat == "svg"){
            getImgInfo('weAboutEnglishImage',function (imgInfo) {
                if(imgInfo.size > 5*1024*1024){
                    alert("图片不能大于5M！");
                    document.querySelector('#weAboutEnglishImage').value = '';
                }else if(type==2 && (imgInfo.width != 200||imgInfo.height != 200)){
                    alert("学校logo图片格式不对！");
                    document.querySelector('#weAboutEnglishImage').value = '';
                    return;
                }else if(type==1 && (imgInfo.width != 560||imgInfo.height != 191)){
                    alert("新闻头图格式不对！");
                    document.querySelector('#weAboutEnglishImage').value = '';
                    return;
                }
                this.state.imgData.showImg = true;
                this.state.imgData.updateImg = true;
                this.state.imgData.imgUrl = imgInfo.src;
                this.setState({imgData: this.state.imgData});
            }.bind(this));
        }else{
           alert('请选择图片文件上传!');
            this.state.imgData.showImg = false;
            this.state.imgData.imgUrl = '';
            this.setState({imgData:this.state.imgData});
        }
    }
    /**
     * 离开的时候清除一下
     */
    componentWillUnmount() {
        this.state.UE.destroy();
    }

    /**
     * 返回上一页
     */
    return(){
        this.context.router.goBack();
    }
    render() {
        let {type,id,imgData,infoData} = this.state;
        let title = '';
        if(type==1){//新闻
            if(id){
                title = '编辑新闻中心';
            }else{
                title = '新增新闻中心';
            }
        }else if(type==2){//案例学校
            if(id){
                title = '编辑案例展示';
            }else{
                title = '新增案例展示';
            }
        }else if(type==3){//合作政策
            if(id){
                title = '编辑合作政策';
            }else{
                title = '新增合作政策';
            }
        }else if(type==4){//合作伙伴
            if(id){
                title = '编辑合作伙伴';
            }else{
                title = '新增合作伙伴';
            }
        }
        return (
            <div className='article'>
                <Form inline>
                    <span style={{fontSize:'24px'}}>{title}</span>
                    <Button bsStyle="info" style={{float:'right'}} onClick={this.return.bind(this)}>返回</Button>
                </Form>

                <form style={{marginTop:'30px'}}>
                    {
                        type == 1||type == 4?
                                <FieldGroup id="weAboutEnglishImage"
                                            accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" type="file"
                                            onChange={this.onChangFile.bind(this)}
                                            label={type==1?"新闻头图":"商家logo"}
                                            help={type==1?"说明：用于新闻中心列表展示图片,尺寸为：宽560*高191px,大小限制5M":"说明：用于生态圈合作伙伴展示图片,尺寸为：宽200*高200px,大小限制5M"}
                                />
                            :''
                    }

                    {
                        imgData.showImg?
                            <img src={imgData.imgUrl} alt=""/>:''
                    }
                    <FieldGroup id="title" type="text" label="标题内容" placeholder="请输入标题" maxLength="100"/>
                    <FormGroup>
                        <ControlLabel>是否置顶</ControlLabel>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <label htmlFor=""><Radio inline name="top" value="true" >是</Radio></label>
                        {' '}
                        <label htmlFor=""><Radio inline name="top" value="false" >否</Radio></label>
                    </FormGroup>

                    <FormGroup>
                        <ControlLabel>是否展示</ControlLabel>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <label htmlFor=""><Radio inline name="show" value="1" >是</Radio></label>
                        {' '}
                        <label htmlFor=""><Radio inline name="show" value="0" >否</Radio></label>
                    </FormGroup>


                    <FormGroup controlId="weAboutEnglishConter">
                        <ControlLabel>简介内容</ControlLabel>
                        <FormControl componentClass="textarea" id="introduce" placeholder="请填写简介内容" maxLength="500"/>
                    </FormGroup>
                    <FormGroup controlId="weAboutEnglishConter">
                        <ControlLabel>文章内容</ControlLabel>
                        <script id="editor" type="text/plain" style={{minHeight:'500px'}}></script>
                    </FormGroup>
                    <Button type="submit" onClick={this.addArticle.bind(this)}>
                        提交
                    </Button>
                </form>
            </div>
        )
    }
}
